#include <thread>
#include <chrono>
#include <dlfcn.h>
#include "qos/qos.h"
#include "napi/native_api.h"
#include "hilog/log.h"

#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3000
#define LOG_TAG "MY_TAG"

static int preloadCost = 0;

static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);

    return sum;
}

static napi_value getPreloadCost(napi_env env, napi_callback_info info)
{
    size_t argc = 0;
    napi_value result = nullptr;

    napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr);

    napi_create_int32(env, preloadCost, &result);
    
    return result;
}

void preloadCb()
{
    pthread_setname_np(pthread_self(), "preload_so");
    OH_QoS_SetThreadQoS(QoS_Level::QOS_USER_INTERACTIVE);
    preloadCost = 0;
    auto preloadStart = std::chrono::high_resolution_clock::now();
    dlopen("libentry1.so", RTLD_NOW);
    dlopen("libentry2.so", RTLD_NOW);
    dlopen("libentry3.so", RTLD_NOW);
    dlopen("libentry4.so", RTLD_NOW);
    dlopen("libentry5.so", RTLD_NOW);
    dlopen("libentry6.so", RTLD_NOW);
    auto preloadFinish = std::chrono::high_resolution_clock::now();
    preloadCost = std::chrono::duration_cast<std::chrono::microseconds>(preloadFinish - preloadStart).count();
    OH_LOG_INFO(LOG_APP, "preload cost time: %{public}d", preloadCost);
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    std::thread preloadThread(preloadCb);
    preloadThread.detach();
    
    napi_property_descriptor desc[] = {
        { "AAAAA", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "getPreloadCost", nullptr, getPreloadCost, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "preload",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterPreloadModule(void)
{
    napi_module_register(&demoModule);
}
